
<template>
  <div :class="{'mobile-target-table': showMobilePage}" class="target-table">
    <div class="entiy-target">
      <Title title="经营体目标" />
      <div v-if="isEdit" class="right-btn">
        <PlainCreateBtn :show-icon="false" style="padding: 8px 11px;" @click="addCount">添加账号</PlainCreateBtn>
        <el-button class="delete-btn" type="danger" plain size="small" @click="delAccount">删除</el-button>
        <el-button class="batch-btn" plain size="small" @click="openBatchAdd">批量添加账号</el-button>
      </div>
    </div>
    <slot v-if="showMobilePage" name="exportBtn"/>
    <div class="btn-container">
      <div class="update-p mr"><img :src="publicTime" alt="更新时间"><span class="grey-title">更新时间：</span>{{ targetData.updateTime | format('YYYY/MM/DD HH:mm') }}</div>
      <div class="update-p flex-1"><img :src="me" alt="更新人"><span class="grey-title">更新人：</span>{{ targetData.updater ? targetData.updater : '--' }}</div>
    </div>
    <!-- max-height="calc(100vh - 285px)" -->
    <el-table
      v-loading="tableLoading"
      :data="mergeData"
      :span-method="arraySpanMethod"
      class="fb-table"
      fit
      border
      empty-text="暂无数据">
      <el-table-column :fixed="selectFixed" align="left" label="所属经营体" min-width="150">
        <template slot-scope="scope">
          <!-- 部门 -->
          <div v-if="!scope.row.isResource" class="flex">
            <img v-if="scope.$index === 0" :src="deptIcon" class="dept-icon" alt="">
            <div v-else class="dot"/>
            <ToolTip :content="scope.row.businessEntiy"/>
          </div>
          <!-- 资源 -->
          <div v-else class="flex-center resource">
            <template v-if="isEdit">
              <el-checkbox v-model="scope.row.delResource" />
              <!-- 添加账号 -->
              <selectWithoutHttp
                v-model="scope.row.platformId"
                :list-data="platformList"
                placeholder="下单平台"
                clearable
                key-name="id"
                label-name="value"
                @change="orderPlatformChange($event, scope.row)"
              />
            </template>
            <!-- 显示账号 -->
            <div v-else class="flex-center platform">
              <platformIcon :data="scope.row.platformName" />
              <ToolTip :content="scope.row.platformName"/>
            </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column :fixed="selectFixed" align="left" label="目标类型" min-width="150">
        <template slot-scope="scope">
          <!-- 部门数据 -->
          <div v-if="!scope.row.isResource">
            {{ scope.row.type | typeFilter }}
          </div>
          <!-- 资源账号 -->
          <div v-else class="account">
            <template v-if="isEdit">
              <!-- 添加账号 -->
              <selectWithUserLoad
                v-if="!scope.row.hideAddResource"
                v-model="scope.row.accountId"
                :key="scope.row.index"
                :loadmore-method="resourceList(scope.row.platformId)"
                :hide-select-list="scope.row.accountId? [{id: scope.row.accountId, value: scope.row.accountName}]:[]"
                :init-load="!!scope.row.initLoadResource"
                key-name="id"
                label-name="value"
                filterable
                clearable
                visible-change-data
                @changeMethod="resourceChange($event, scope.row)"
              />
            </template>
            <!-- 显示账号 -->
            <ToolTip v-else :content="scope.row.accountName"/>
          </div>
        </template>
      </el-table-column>
      <el-table-column :align="isEdit?'left':'right'" label="总目标(万)" min-width="120">
        <template slot-scope="scope">
          <div v-if="isEdit && totalTargetEdit(scope.row)" class="edit-cell">
            <el-input
              v-model="scope.row.totalTarget"
              oninput="if(value>9999999)value=9999999;if(value<0)value=0"
              type="number"
              size="small"
              placeholder="请输入"
              @change="numberInputChange(scope.row, 'totalTarget')"
              @mousewheel.native.prevent
            />
          </div>
          <!-- 录入差额 -->
          <div v-else-if="scope.row.type === 2" :class="{'red-number': scope.row.totalTarget > 0, 'green-number': scope.row.totalTarget < 0, 'cell-bg': isEdit}">
            <ToolTip
              :content="scope.row.totalTarget > 0 ? '+' + moneyFilter(scope.row.totalTarget) : moneyFilter(scope.row.totalTarget)"
              :tool-tip="isEdit?'不可编辑':''" />
          </div>
          <!-- 不可编辑 -->
          <div v-else :class="{'cell-bg': isEdit}">
            <ToolTip :content="scope.row.totalTarget | moneyFilter" :tool-tip="isEdit?'不可编辑':''" />
          </div>
        </template>
      </el-table-column>
      <el-table-column :align="isEdit?'left':'right'" label="录入差额(万)" min-width="120">
        <template slot-scope="scope">
          <div :class="{'red-number': scope.row.rowDifference > 0, 'green-number': scope.row.rowDifference < 0, 'cell-bg': isEdit}">
            <ToolTip :content="scope.row.rowDifference > 0 ? '+' + moneyFilter(scope.row.rowDifference) : moneyFilter(scope.row.rowDifference)" :tool-tip="isEdit?'不可编辑':''" />
          </div>
        </template>
      </el-table-column>
      <!-- 月份数据 -->
      <el-table-column
        v-for="item in monthList"
        :key="item.key"
        :label="item.label+'(万)'"
        :align="isEdit?'left':'right'"
        min-width="110">
        <template slot-scope="scope">
          <el-input
            v-if="isEdit && totalTargetEdit(scope.row) && monthEdit(item)"
            v-model="scope.row[item.key]"
            oninput="if(value>9999999)value=9999999;if(value<0)value=0"
            type="number"
            size="small"
            placeholder="请输入"
            @change="numberInputChange(scope.row, item.key)"
            @mousewheel.native.prevent
          />
          <!-- 录入差额 -->
          <div v-else-if="scope.row.type === 2" :class="{'red-number': scope.row[item.key] > 0, 'green-number': scope.row[item.key] < 0, 'cell-bg': isEdit}">
            <ToolTip :content="scope.row[item.key] > 0 ? '+'+moneyFilter(scope.row[item.key]) : moneyFilter(scope.row[item.key])" :tool-tip="isEdit?'不可编辑':''" />
          </div>
          <!-- 不可编辑 -->
          <div v-else :class="{'cell-bg': isEdit}">
            <ToolTip :content="scope.row[item.key] | moneyFilter" :tool-tip="isEdit?'不可编辑':''" />
          </div>
        </template>
      </el-table-column>
    </el-table>
    <div v-if="targetData.accounts && targetData.accounts.length && showMobilePage" class="pagination-pager">
      <el-button :disabled="page === 1" class="page-jump-btn" title="上一页" size="mini" icon="el-icon-arrow-left" @click="handleCurrentChange(page-1)" />
      <el-button :disabled="setNextBtnDisabled" class="page-jump-btn" title="下一页" size="mini" icon="el-icon-arrow-right" style="margin-right: 5px" @click="handleCurrentChange(page+1)" />
      <el-pagination
        :current-page="page"
        :page-size="perPage"
        :total="targetData.accounts.length"
        :page-sizes="[10,20, 50, 100, 250, 500]"
        layout="total, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange" />
    </div>
    <!-- width: 'calc((100% - 224px) - 32px - 320px)' -->
    <fixed-pagination :style="(isEdit || device === 'mobile')?'':{}" :padding-left="(isEdit || !isShowLeft)?0:320">
      <div v-if="!isEdit" class="center">
        <el-button :disabled="!(isFuturetime() || hasRouteAuth('crm:target:editAll'))" type="primary" size="small" class="submit-btn" @click="openEdit">编辑</el-button>
      </div>
      <div v-else class="center">
        <PlainCreateBtn :loading="editLoading" :show-icon="false" style="padding: 8px 11px;" @click="save(false)">快速保存</PlainCreateBtn>
        <el-button :loading="editLoading" type="primary" size="small" class="submit-btn" @click="save(true)">保存</el-button>
        <el-button class="back-btn cancel-btn-style" type="info" size="small" @click="handleCancel">取消</el-button>
      </div>
      <div v-if="targetData.accounts && targetData.accounts.length && !showMobilePage" class="pagination-pager">
        <el-button :disabled="page === 1" class="page-jump-btn" title="上一页" size="mini" icon="el-icon-arrow-left" @click="handleCurrentChange(page-1)" />
        <el-button :disabled="setNextBtnDisabled" class="page-jump-btn" title="下一页" size="mini" icon="el-icon-arrow-right" style="margin-right: 5px" @click="handleCurrentChange(page+1)" />
        <el-pagination
          :current-page="page"
          :page-size="perPage"
          :total="targetData.accounts.length"
          :page-sizes="[10,20, 50, 100, 250, 500]"
          layout="sizes, total, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>
    </fixed-pagination>
    <resourceDrawer ref="resourceDrawerRef" @getResources="getResources" />
  </div>
</template>

<script>
// tools
import { moneyFilter } from '@/filters/number';
import { hasRouteAuth } from '@/utils/permission';
import { showModal } from '@/utils/message';
import ElMessage from '@/utils/message';
import { format } from '@/filters/date';
import math from '@/utils/math';
// import _ from 'lodash';
// components
import Title from '@/components/Title';
import resourceDrawer from '@/components/Common/resourceDrawer';
import selectWithUserLoad from '@/components/Common/selectWithUserLoad';
import selectWithoutHttp from '@/components/Common/selectWithoutHttp';
import platformIcon from '@/components/Common/platformIcon';
// img
import me from '@/assets/todo/me.png';
import publicTime from '@/assets/todo/publicTime.png';
import deptIcon from '@/assets/mengli/inventory/gc_icon.png';
// mixins
import mobileTable from '@/mixins/mobileTable';
// api
import { platformList, getResource } from '@/api/select';
import { mapState } from 'vuex';
import { putTargetData } from '@/api/target';
export default {
  components: { Title, platformIcon, resourceDrawer, selectWithUserLoad, selectWithoutHttp },
  filters: {
    moneyFilter,
    format,
    typeFilter(val) {
      return {
        0: '本级目标',
        1: '子级目标',
        2: '录入差额'
      }[val];
    }
  },
  mixins: [mobileTable],
  props: {
    curDept: {
      type: Object,
      default: () => {
        return {};
      }
    },
    selectYear: {
      type: Number,
      default: 2021
    },
    isEdit: {
      type: Boolean,
      default: false
    },
    targetData: {
      type: Object,
      default: () => {
        return {};
      }
    },
    tableLoading: {
      type: Boolean,
      default: false
    },
    isShowLeft: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      me, deptIcon,
      publicTime,
      platformList: [],
      page: 1,
      perPage: 10,
      monthList: [
        { label: '1月', key: 'january', month: 1 }, { label: '2月', key: 'february', month: 2 }, { label: '3月', key: 'march', month: 3 },
        { label: '4月', key: 'april', month: 4 }, { label: '5月', key: 'may', month: 5 }, { label: '6月', key: 'june', month: 6 },
        { label: '7月', key: 'july', month: 7 }, { label: '8月', key: 'august', month: 8 }, { label: '9月', key: 'september', month: 9 },
        { label: '10月', key: 'october', month: 10 }, { label: '11月', key: 'november', month: 11 }, { label: '12月', key: 'december', month: 12 }
      ],
      accountLoading: false,
      editLoading: false,
      accountList: [],
      platformToResource: new Map(),
      notMath: false,
      delAccounts: [] // 被删除账号id
    };
  },
  computed: {
    mergeData() {
      const deptList = this.targetData.items || []; // 部门列表
      const accountsList = this.targetData.accounts || []; // 资源列表
      const allList = deptList.concat(accountsList); // 部门列表与不分页的资源列表和
      const splitAccountsList = this.handelData(accountsList); // 本地分页后的账户列表
      const mergeList = deptList.concat(splitAccountsList);
      this.mathNum(allList);
      return mergeList;
    },
    setNextBtnDisabled() {
      return (this.page * this.perPage) - this.targetData.accounts.length >= 0;
    },
    curMonth() {
      return this.targetData.curMonth;
    },
    ...mapState({
      'device': state => state.app.device
    })
  },
  created() {
    this.getPlatForm();
  },
  methods: {
    hasRouteAuth,
    moneyFilter,
    isFuturetime(item) {
      // 是否是未来的时间
      // 前几年的数据
      const curYear = new Date().getFullYear();
      if (this.selectYear < curYear) {
        return false;
      } else if (this.selectYear === curYear && item && item.month) {
        return this.curMonth <= item.month;
      }
      return true;
    },
    // 获取数据
    getPlatForm() {
      platformList().then(({ code, data }) => {
        this.platformList = data;
      });
    },
    // 批量增加账号
    openBatchAdd() {
      this.$refs.resourceDrawerRef.openDrawer();
    },
    getResources(list) { // 获取选择的资源
      this.notMath = true;
      const batchAccount = list.map(item => {
        return {
          platformId: item.platformType,
          accountId: item.mediumId,
          accountName: item.resourceName,
          isResource: true,
          delResource: null,
          hideAddResource: false,
          initLoadResource: false // 是否一进来就请求资源
        };
      });
      const data = batchAccount.concat(this.targetData.accounts);
      data.forEach((i, index) => {
        i.index = index + 1; // 下拉组件需要用到，当作key
      });
      this.targetData.accounts = data;
    },
    // 批量增加账号 end
    // 本地分页
    handleSizeChange(val) {
      this.perPage = val;
    },
    handleCurrentChange(val) {
      this.page = val;
    },
    handelData(data) {
      return data.slice((this.page - 1) * this.perPage, this.page * this.perPage);
    },
    // 计算差额
    mathNum(list) {
      if (list.length > 1) {
        // 计算列录入差额
        const res = {
          totalTarget: 0, january: 0, february: 0, march: 0,
          april: 0, may: 0, june: 0, july: 0, august: 0,
          september: 0, october: 0, november: 0, december: 0
        };
        list.forEach(item => {
          if (item.type !== 0 && item.type !== 2) {
            for (const key in res) {
              res[key] = math.add(res[key], this.nanToZero(item[key]));
            }
          }
        });
        for (const key in res) {
          list[1][key] = math.subtract(res[key], list[0][key]);
        }
        this.$emit('updateTotalInputTarget', res.totalTarget);
      }
      // 计算行录入差额
      list.forEach(item => {
        item.rowDifference = math.subtract(this.monthSum(item), this.nanToZero(item.totalTarget));
      });
    },
    nanToZero(num) {
      return isNaN(parseFloat(num)) ? 0 : parseFloat(num);
    },
    monthSum(item) {
      let sum = 0;
      this.monthList.forEach(ele => {
        sum = math.add(sum, this.nanToZero(item[ele.key]));
      });
      return sum;
    },
    addCount() {
      this.targetData.accounts.unshift({ isResource: true, delResource: null, hideAddResource: false, accountId: null });
    },
    // 获取账户名称的列表
    resourceList(platformId) {
      const promise = function(params) {
        return new Promise(async(resolve, reject) => {
          if (!platformId) {
            const initData = { data: { items: [], page: 1, perPage: 15 }};
            resolve(initData);
            return;
          }
          params.resourceName = '';
          if (params.userName) params.resourceName = params.userName;
          params.platformId = platformId;
          delete params.value;
          delete params.userName;

          getResource(params).then(res => {
            resolve(res);
          }).catch(err => {
            reject(err);
          });
        });
      };
      return promise;
    },
    /**
     * 参数改变时调用的方法  change methods
     */
    orderPlatformChange(platformId, row) {
      row.initLoadResource = true; // 是否一进来就请求资源
      // 获取资源列表
      row.hideAddResource = true;
      row.accountId = '';
      row.accountName = '';
      this.$nextTick(() => {
        row.hideAddResource = false;
      });
    },
    resourceChange(item, row) {
      row.accountName = item.value;
    },
    // 编辑模式。操作
    delAccount() {
      const delIndexArr = [];
      this.targetData.accounts.forEach((item, index) => {
        if (item.delResource) {
          delIndexArr.push(index);
          this.delAccounts.push(item.id);
        }
      });
      this.delAccounts = this.delAccounts.filter(i => { return !!i; });
      if (delIndexArr.length > 0) {
        showModal('请确定删除所选账号', '', {
          iconClass: 'del-icon'
        }).then(() => {
          // 用splice删除多个元素会位置不对
          // this.targetData.accounts.splice(item, 1);
          delIndexArr.sort((a, b) => {
            return b - a;
          });
          delIndexArr.forEach(delIndex => {
            for (let m = this.targetData.accounts.length - 1; m >= 0; m--) {
              if (m === delIndex) {
                this.targetData.accounts.splice(delIndex, 1);
                return;
              }
            }
          });
          this.targetData.accounts.forEach(item => {
            this.$set(item, 'delResource', false);
          });
        }).catch(() => {
          return false;
        });
      } else {
        ElMessage.warning('请选择要删除的账号');
      }
    },
    openEdit() {
      this.$emit('goEdit');
    },
    async save(toRead = false) {
      try {
        const targetData = JSON.parse(JSON.stringify(this.targetData));
        const zeroKey = this.monthList.concat({ label: '总目标', key: 'totalTarget' });
        // 只保存填写了下单平台和账号的account
        const validAccounts = targetData.accounts.filter(item => {
          return item.accountId && item.platformId;
        });
        // 没填的置为0
        const validItems = targetData.items.filter(item => {
          return item.type !== 2;
        });
        zeroKey.forEach(item => {
          validAccounts.forEach(ele => {
            ele[item.key] = ele[item.key] || 0;
          });
          validItems.forEach(e => {
            e[item.key] = e[item.key] || 0;
          });
        });
        const params = {
          id: this.curDept.id || 0,
          year: this.selectYear,
          items: validItems,
          accounts: validAccounts
        };
        if (this.delAccounts.length > 0) {
          params.delAccounts = this.delAccounts;
        }
        this.editLoading = true;
        await putTargetData(params);
        this.editLoading = false;
        if (toRead) {
          // 保存跳转至编辑
          this.$emit('goTarget', true);
        } else {
          // 快速保存，需要更新时间和更新人
          this.$emit('goTarget', false);
        }
      } catch (err) {
        console.log(err);
      }
    },
    handleCancel() {
      // 返回目标管理
      showModal('请确认是否离开，离开后将不保存本次编辑数据', '', {
        iconClass: 'del-icon'
      }).then(() => {
        // 取消重置数据
        this.$emit('goTarget', true);
      }).catch(() => {
        return false;
      });
    },
    arraySpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 0 && rowIndex === 0) {
        return {
          rowspan: 2,
          colspan: 1
        };
      } else if (rowIndex === 1 && columnIndex === 0) {
        return [0, 0];
      }
    },
    totalTargetEdit(row) {
      // 本级目标是不是一级经营体，是的话可以编辑，不是的话可以编辑子级目标和账号目标
      return (row.businessEntiyId === 0 && row.type === 0) || (row.businessEntiyId !== 0 && (row.isResource || row.type === 1));
    },
    monthEdit(item) {
      return this.hasRouteAuth('crm:target:editAll') || this.isFuturetime(item);
    },
    numberInputChange(item, key) {
      if (item[key]) item[key] = Number(item[key]).toFixed(2);
    }
  }
};
</script>

<style lang="scss" scoped>
.target-table {
  padding-bottom: 60px;
  .entiy-target {
    margin-top: 32px;
    display: flex;
    align-items: center;
  }
}
.btn-container {
  display: flex;
  align-items: center;
  margin: 16px 0;
  padding: 0 9px;
  .flex-1 {
    flex:1;
  }
  .right-btn{
    text-align: right;
    display: flex;
    align-items: center;
  }
  .update-p {
    display: flex;
    align-items: center;
    font-size: 14px;
    flex-shrink: 0;
    min-width: 150px;
    img {
      width: 15px;
      height: 15px;
      margin-right: 4px;
    }
    .grey-title {
      color: #999;
    }
    &.mr {
      margin-right: 50px;
    }
  }
}
.el-table {
  // overflow-y: scroll;
  // &::before{
  //   height: 0;
  // }
  &::v-deep .el-table__row {
    td {
      padding-top: 0;
      padding-bottom: 0;
      background-color: #fff !important;
    }
    .cell {
      height: 56px;
      line-height: 56px;
      padding: 0;
      >div {
        padding: 0 8px;
      }
      .el-input-number {
         width: 100%;
      }
      .el-input__inner {
        position: relative;
        height: 56px;
        border-radius: 0;
        padding-right: 0;
        padding-left: 0;
        border-color: transparent;
        text-align: left;
      }
      .el-select {
        .el-input__inner {
          padding-left: 8px;
        }
      }
    }
  }
  .account, .resource {
    &::v-deep .el-input__inner {
      text-align: left !important;
    }
  }
  .resource {
    &::v-deep {
      .el-checkbox {
        // width: 48px;
        height: 55px;
        line-height: 55px;
        // text-align: center;
        padding: 0 16px 0 8px;
        border-right: 1px solid #EBEEFD;
      }
    }
  }
  .platform {
    padding-left: 0px;
    // width: 100px;
    // height: 55px;
    // border-right: 1px solid #EBEEFD;
  }
  .red-number {
    color:#FF4E5F;
  }
  .green-number {
    color:#31CC9C;
  }
  .cell-bg {
    background-color: #f5f7fa;
  }
}
.el-row {
  &.center {
    display: flex;
    align-items: center;
    margin: 10px 0;
  }
  .right-btn{
    text-align: right;
  }
}
.delete-btn {
  background-color: #fff;
  width: 48px;
  padding: 8px 0;
  color: #FF4E5F;
  text-align: center;
  border-color: #FF4E5F;
  border-radius: 4px;
}
.batch-btn {
  padding: 8px 10px;
  border: 1px solid #dddddd;
  border-radius: 4px;
  color: #666666;
}
.page-jump-btn {
  width: 20px;
  height: 20px;
  padding: 0;
}
.flex {
  display: flex;
  align-items: center;
}
.dot {
  width: 6px;
  height: 6px;
  background: #406eff;
  border-radius: 50%;
  margin-right: 6px;
  flex-shrink: 0;
}
.dept-icon {
  width: 22px;
  margin-right: 3px;
}
.pagination-pager {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  &::v-deep {
   .el-pagination__jump {
      margin-left: 0;
    }
  }

}
.mobile-target-table {
  .entiy-target {
    display: block;
    .right-btn {
      margin-top: 12px;
    }
  }
  .btn-container {
    display: block;
    .update-p {
      margin-bottom: 12px;
    }
  }
}
</style>
